<template>
	<view class="container">
		<scroll-view class="detail-content" scroll-y v-if="detailData">
			<!-- 状态信息 -->
			<view class="info-section">
				<view class="section-title">状态信息</view>
				<view class="status-grid">
					<view class="status-item">
						<text class="status-label">核实状态</text>
						<view class="status-badge" :class="statusClass">
							{{statusText}}
						</view>
					</view>
					<view class="status-item">
						<text class="status-label">提交时间</text>
						<text class="status-value">{{formatTime(detailData.create_time)}}</text>
					</view>
					<view class="status-item" v-if="detailData.feedback_time">
						<text class="status-label">反馈时间</text>
						<text class="status-value">{{formatTime(detailData.feedback_time)}}</text>
					</view>
				</view>
			</view>

			<!-- 基础信息 -->
			<view class="info-section">
				<view class="section-title">基础信息</view>
				<view class="info-grid">
					
					<view class="info-item">
						<text class="info-label">商品型号</text>
						<text class="info-value">{{(detailData.goods && detailData.goods.model) || ''}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">品牌</text>
						<text class="info-value">{{(detailData.brand_name && detailData.brand_name) || ''}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">商品产地</text>
						<text class="info-value">{{getGoodsOrigin()}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">商品包装</text>
						<text class="info-value">{{getGoodsPackage()}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">发货地</text>
						<text class="info-value">{{getDispatchPlace()}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">商品数量</text>
						<text class="info-value">{{detailData.number || ''}} 件</text>
					</view>
					<view class="info-item">
						<text class="info-label">商品价格</text>
						<text class="info-value price">¥{{detailData.price || ''}}</text>
					</view>
					<view class="info-item full-width" v-if="detailData.verify_memo">
						<text class="info-label">用户备注</text>
						<text class="info-value">{{detailData.verify_memo}}</text>
					</view>
				</view>
			</view>

			<!-- 核实信息 -->
			<view class="info-section">
				<view class="section-title">核实信息</view>

				<!-- 库存数量 -->
				<view class="form-item">
					<text class="form-label">库存数量</text>
					<uv-input v-if="isEditable" v-model="detailData.sku.stock" placeholder="请输入库存数量" type="number"
						border="bottom" :disabled="!isEditable"></uv-input>
					<text v-else class="form-value">{{getStockNumber()}} 件</text>
				</view>

				<!-- 发货地区 -->
				<view class="form-item">
					<text class="form-label">发货地区</text>
					<view v-if="isEditable" class="region-picker">
						<uv-picker ref="picker" :columns="regionColumns" keyName="name" @confirm="regionConfirm"
							@change="regionChange" :defaultIndex="regionDefaultIndex"></uv-picker>

						<view class="input-wrapper" @click="openRegionPicker">
							<uv-input v-model="selectedRegionText" placeholder="请选择发货地区" border="bottom" readonly
								:suffix="isEditable ? 'arrow-down' : ''" :disabled="!isEditable"></uv-input>
						</view>
					</view>
					<text v-else class="form-value">{{getShipmentArea()}}</text>
				</view>

				<!-- 温馨提示 -->
				<view class="tip-section">
					<text class="tip-text">为避免用户下单后发货异常，请选择正确的发货地！</text>
				</view>

				<!-- 核实图片 -->
				<view class="form-item">
					<text class="form-label">核实图片</text>
					<view v-if="isEditable">
						<uv-upload :fileList="verifyData.verify_images" @afterRead="afterRead" @delete="deletePic"
							:maxCount="1" :previewFullImage="true" :disabled="!isEditable"></uv-upload>
					</view>
					<view v-else class="image-preview-readonly">
						<view v-if="detailData.feedback_image" class="image-list">
							<uv-image :src="detailData.feedback_image" width="120" height="120" radius="8"
								@click="previewImage(detailData.feedback_image)"></uv-image>
						</view>
						<text v-else class="no-image">暂无图片</text>
					</view>
				</view>

				<!-- 核实备注 -->
				<view class="form-item">
					<text class="form-label">核实备注</text>
					<uv-textarea v-if="isEditable" v-model="verifyData.verify_memo" placeholder="请输入核实备注"
						:disabled="!isEditable" :count="true" height="120"></uv-textarea>
					<view v-else class="memo-content-readonly">
						<text class="memo-text">{{detailData.feedback_memo || '暂无备注'}}</text>
					</view>
				</view>

				<!-- 提交按钮 -->
				<view class="action-buttons" v-if="isEditable">
					<uv-button type="primary" shape="circle" @click="submitVerify" :loading="submitting"
						:text="submitting ? '提交中...' : '提交核实'"></uv-button>
					<uv-button type="default" shape="circle" @click="cancelVerify" text="取消"
						:customStyle="{}"></uv-button>
				</view>
			</view>

			<!-- 商品图片 -->
			<view class="info-section" v-if="getGoodsImage()">
				<view class="section-title">商品图片</view>
				<view class="goods-image">
					<uv-image :src="getGoodsImage()" width="300" height="300" radius="12" mode="aspectFill"
						@click="previewImage(getGoodsImage())"></uv-image>
				</view>
			</view>
		</scroll-view>

		<!-- 加载状态 -->
		<uv-loading-icon v-if="loading" mode="circle" size="36"></uv-loading-icon>

		<!-- 错误状态 -->
		<view class="error-state" v-if="!loading && !detailData">
			<uv-icon name="error" size="120" color="#ccc"></uv-icon>
			<text class="error-text">加载失败</text>
			<uv-button type="primary" shape="circle" @click="loadDetail" text="重新加载" :customStyle="{
					marginTop: '30rpx',
					width: '200rpx'
				}"></uv-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loading: false,
				submitting: false,
				recordId: null,
				detailData: null,
				// 省市选择器
				regionColumns: [],
				regionDefaultIndex: [0, 0], // 默认选中第一列的第一个省和第一个市
				provinceList: [],
				cityList: [],
				provinceId: '',
				cityId: '',
				selectedProvince: '',
				selectedCity: '',
				selectedRegionText: '',
				// 核实数据
				verifyData: {
					stock_number: '',
					verify_memo: '',
					verify_images: [],
					shipment_province_code: '',
					shipment_city_code: ''
				},
				// 状态类名映射
				statusClassMap: {
					'pending': 'status-pending',
					'verified': 'status-verified',
					'expired': 'status-expired'
				},
				// 状态文本映射
				statusTextMap: {
					'pending': '待核实',
					'verified': '已核实',
					'expired': '已失效'
				}
			};
		},
		computed: {
			// 状态类名
			statusClass() {
				if (!this.detailData) return 'status-pending';
				return this.statusClassMap[this.detailData.verify_status] || 'status-pending';
			},
			// 状态文本
			statusText() {
				if (!this.detailData) return '未知状态';
				return this.statusTextMap[this.detailData.verify_status] || '未知状态';
			},
			// 是否可编辑
			isEditable() {
				return this.detailData && this.detailData.verify_status === 'pending';
			}
		},
		onLoad(options) {
			if (options.id) {
				this.recordId = options.id;
				this.loadDetail();
			} else {
				this.$wanlshop.msg('参数错误');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
			// 确保省份数据已加载
			this.loadProvinceData();
		},
		methods: {
			// 加载详情
			async loadDetail() {
				this.loading = true;

				try {
					const res = await uni.$uv.http.get('/supplier/getVerifyDetail', {
						params: {
							record_id: this.recordId
						}
					});

					if (res.res.code === 1) {
						this.detailData = res.res.data;
						// 初始化表单数据
						this.initVerifyData();
					}
				} catch (error) {
					console.error('获取核实详情失败:', error);
					this.$wanlshop.msg('获取失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},

			// 初始化核实数据
			initVerifyData() {
				if (this.detailData) {
					this.verifyData.stock_number = this.getStockNumber();
					this.verifyData.verify_memo = this.detailData.feedback_memo || '';

					// 初始化图片数据
					if (this.detailData.feedback_image) {
						this.verifyData.verify_images = [{
							url: this.detailData.feedback_image,
							status: 'success'
						}];
					}
				}
			},

			// 打开地区选择器
			openRegionPicker() {
				this.$refs.picker.open();
			},

			// 加载省份数据
			async loadProvinceData() {
				// 如果已经加载过省份数据，直接返回
				if (this.provinceList.length > 0) {
					return;
				}

				try {
					const res = await uni.$uv.http.get('/wanlshop/common/area');
					if (res.res.code === 1) {
						this.provinceList = res.res.data;

						// 构建地区选择器数据结构
						this.buildRegionColumns();
					}
				} catch (error) {
					console.error('加载省份数据失败:', error);
				}
			},

			// 构建地区选择器数据结构
			buildRegionColumns() {
				if (this.provinceList.length === 0) return;

				// 第一列：省份
				const provinceColumn = this.provinceList.map(item => ({
					name: item.name,
					id: item.id
				}));

				// 第二列：默认第一个省份的城市
				const firstProvince = this.provinceList[0];
				const cityColumn = firstProvince.city ? firstProvince.city.map(item => ({
					name: item.name,
					id: item.id
				})) : [];

				// 设置地区选择器列数据
				this.regionColumns = [provinceColumn, cityColumn];
			},

			regionChange(e) {
				const {
					columnIndex,
					index,
					value
				} = e;

				// 第一列（省份）变化时，更新第二列（城市）
				if (columnIndex === 0) {
					const selectedProvince = this.provinceList[index];
					if (selectedProvince && selectedProvince.city) {
						const cityColumn = selectedProvince.city.map(item => ({
							name: item.name,
							id: item.id
						}));

						// 更新第二列数据
						this.$refs.picker.setColumnValues(1, cityColumn);

						// 更新默认选中第一个城市
						if (selectedProvince.city.length > 0) {
							this.provinceId = selectedProvince.id;
							this.cityId = selectedProvince.city[0].id;
							this.selectedProvince = selectedProvince.name;
							this.selectedCity = selectedProvince.city[0].name;
							this.selectedRegionText = selectedProvince.name + '-' + selectedProvince.city[0].name;
						}
					}
				}
			},

			regionConfirm(e) {
				const province = e.value[0];
				const city = e.value[1];

				if (province && city) {
					this.provinceId = province.id;
					this.cityId = city.id;
					this.selectedProvince = province.name;
					this.selectedCity = city.name;
					this.selectedRegionText = province.name + '-' + city.name;
				}
			},

			// 获取商品产地
			getGoodsOrigin() {
				if (this.detailData.goods && this.detailData.goods.origin) {
					return this.detailData.goods.origin;
				}
				return '';
			},

			// 获取商品包装
			getGoodsPackage() {
				if (this.detailData.goods && this.detailData.goods.package) {
					return this.detailData.goods.package;
				}
				return '';
			},

			// 获取发货地
			getDispatchPlace() {
				if (this.detailData.goods && this.detailData.goods.place_of_shipment) {
					const placeMap = {
						'1533': '东北',
					};
					return placeMap[this.detailData.goods.place_of_shipment] || this.detailData.goods.place_of_shipment;
				}
				return '';
			},

			// 获取库存数量
			getStockNumber() {
				if (this.detailData.sku && this.detailData.sku.stock) {
					return this.detailData.sku.stock.toString();
				}
				return '';
			},

			// 获取发货地区
			getShipmentArea() {
				if (this.detailData.city && this.detailData.city !== '-') {
					return this.detailData.city;
				}
				return '';
			},

			// 获取商品图片
			getGoodsImage() {
				if (this.detailData.goods && this.detailData.goods.image) {
					return this.detailData.goods.image;
				}
				return '';
			},

			// 图片上传
			async afterRead(event) {
				const {
					file
				} = event;
				// 添加文件到列表，状态为上传中
				const newFiles = [].concat(file).map(item => ({
					...item,
					status: 'uploading',
					message: '上传中'
				}));
				this.verifyData.verify_images = [...this.verifyData.verify_images, ...newFiles];

				// 逐个上传文件
				for (let i = 0; i < newFiles.length; i++) {
					const originalIndex = this.verifyData.verify_images.length - newFiles.length + i;

					try {
						const result = await this.uploadFilePromise(newFiles[i].url, newFiles[i].name);

						// 处理图片路径，去掉域名只保留相对路径
						let imageUrl = result.fullurl || result.url;
						if (imageUrl) {
							// 移除域名部分，只保留路径
							imageUrl = imageUrl.replace(/^https?:\/\/[^\/]+/, '');
						}

						this.$set(this.verifyData.verify_images, originalIndex, {
							...newFiles[i],
							status: 'success',
							message: '上传成功',
							url: imageUrl
						});

					} catch (error) {
						console.error('上传失败', error);

						this.$set(this.verifyData.verify_images, originalIndex, {
							...newFiles[i],
							status: 'failed',
							message: '上传失败：' + (error.message || '未知错误')
						});
					}
				}
			},

			async uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: '/wanlshop.common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let result = JSON.parse(res.data);
							let url = result.data.url;
							setTimeout(() => {
								resolve(result.data)
							}, 1000)
						}
					});
				})
			},

			// 删除图片
			deletePic(event) {
				this.verifyData.verify_images.splice(event.index, 1);
			},

			// 提交核实
			async submitVerify() {
				if (!this.verifyData.stock_number) {
					this.$wanlshop.msg('请输入库存数量');
					return;
				}

				if (!this.selectedProvince || !this.selectedCity) {
					this.$wanlshop.msg('请选择发货地区');
					return;
				}

				this.submitting = true;

				try {
					const formData = {
						record_id: this.recordId,
						feedback_number: this.verifyData.stock_number,
						feedback_memo: this.verifyData.verify_memo,
						feedback_image: this.verifyData.verify_images.map(img => img.url).join(','),
						province_id: this.provinceId,
						city_id: this.cityId
					};

					// 调用提交接口
					const res = await uni.$uv.http.post('/supplier/verifyStock', formData);
					if (res.res.code === 1) {
						this.$wanlshop.msg(res.res.msg);
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						this.$wanlshop.msg(res.res.msg || '提交失败');
					}

				} catch (error) {
					console.error('提交核实失败:', error);
					this.$wanlshop.msg('提交失败，请稍后重试');
				} finally {
					this.submitting = false;
				}
			},

			// 取消核实
			cancelVerify() {
				uni.navigateBack();
			},

			// 预览图片
			previewImage(url) {
				uni.previewImage({
					urls: [url],
					current: url
				});
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '未知时间';
				const date = new Date(timestamp * 1000);
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.detail-content {
		height: calc(100vh - 88rpx);
		padding: 30rpx;
		box-sizing: border-box;
	}

	.info-section {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 25rpx;
			position: relative;
			padding-left: 20rpx;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 8rpx;
				height: 32rpx;
				width: 6rpx;
				background-color: #2979ff;
				border-radius: 3rpx;
			}
		}
	}

	/* 基础信息网格 */
	.info-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;

		.info-item {
			display: flex;
			flex-direction: column;
			padding: 20rpx;
			background: #f8fafc;
			border-radius: 12rpx;

			&.full-width {
				grid-column: 1 / -1;
			}

			.info-label {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 8rpx;
			}

			.info-value {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;

				&.price {
					color: #ff7900;
					font-weight: 600;
				}
			}
		}
	}

	/* 表单项目 */
	.form-item {
		margin-bottom: 30rpx;

		.form-label {
			display: block;
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			margin-bottom: 15rpx;
		}

		.form-value {
			font-size: 28rpx;
			color: #666;
			background: #f8fafc;
			border-radius: 12rpx;
			padding: 20rpx;
			display: block;
		}

		/* 地区选择器 */
		.region-picker {
			position: relative;
		}

		/* 图片预览只读状态 */
		.image-preview-readonly {
			.no-image {
				font-size: 26rpx;
				color: #999;
				background: #f8fafc;
				border-radius: 12rpx;
				padding: 40rpx 20rpx;
				display: block;
				text-align: center;
			}

			.image-list {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
			}
		}

		/* 备注只读状态 */
		.memo-content-readonly {
			background: #f8fafc;
			border-radius: 12rpx;
			padding: 20rpx;

			.memo-text {
				font-size: 28rpx;
				color: #666;
				line-height: 1.4;
			}
		}
	}

	/* 温馨提示 */
	.tip-section {
		display: flex;
		align-items: flex-start;
		background: #fff8e8;
		border: 1rpx solid #ffd591;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 25rpx;

		.tip-text {
			flex: 1;
			font-size: 24rpx;
			color: #ff7900;
			line-height: 1.4;
		}
	}

	/* 操作按钮 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-top: 30rpx;
	}

	/* 商品图片 */
	.goods-image {
		display: flex;
		justify-content: center;
	}

	/* 状态信息 */
	.status-grid {
		display: flex;
		flex-direction: column;
		gap: 20rpx;

		.status-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.status-label {
				font-size: 28rpx;
				color: #666;
			}

			.status-value {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
			}

			.status-badge {
				padding: 8rpx 20rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				font-weight: 500;

				&.status-pending {
					background: #fff0e8;
					color: #ff7900;
				}

				&.status-verified {
					background: #e8f7f0;
					color: #19be6b;
				}

				&.status-expired {
					background: #f5f5f5;
					color: #999;
				}
			}
		}
	}

	/* 错误状态 */
	.error-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 0;
		text-align: center;

		.error-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #999;
		}
	}
</style>